import { catalog, customer, security, store } from "@mall/api-services"
import { Drawer } from "antd-mobile"
import * as _ from "lodash"
import * as React from "react"
import { useEffect, useState } from "react"
import { useHistory, useParams } from "react-router-dom"
import Button from "../components/button"
import Divider from "../components/divider"
import Flex from "../components/flex"
import ProductPrice from "../components/product/product-price"
import Space from "../components/space"
import WhiteSpace from "../components/white-space"
import WingBlank from "../components/wing-blank"
import Icon from "../icon"
import OptionSelections from "./option-selections"

import classes from "./product-detail.module.scss"
import ProductImages from "./product-images"

interface ProductCardProps {
  children: React.ReactNode
}

function ProductCard(props: ProductCardProps) {
  const { children } = props
  return (<>
    <div className={classes.productCard}>
      <WhiteSpace/>
      <WingBlank>
        {children}
      </WingBlank>
      <WhiteSpace/>
    </div>
  </>)
}

interface IconButtonProps {
  icon: React.ReactNode
  children: React.ReactNode
  onClick?: () => void
}

function IconButton(props: IconButtonProps) {
  const { icon, onClick, children } = props
  return (
    <WingBlank size="sm">
      <Flex direction="column"
            alignItems="center"
            onClick={onClick}>
        {icon}
        <span style={{ fontSize: "12px" }}>{children}</span>
      </Flex>
    </WingBlank>)
}

interface CardItemProps {
  left: React.ReactNode
  right?: React.ReactNode
  children?: React.ReactNode
  onClick?: () => void
}

function CardItem(props: CardItemProps) {
  const { left, children, right = <Icon type="right" size="xxs"/>, onClick } = props
  return (
    <>
      <WhiteSpace/>
      <Flex alignItems="center" justifyContent="space-between"
            className={classes.productCardItem}
            onClick={onClick}>
        <div className={classes.productCardItemLeft}>{left}</div>
        <div className={classes.productCardItemContent}>{children}</div>
        <div className={classes.productCardItemRight}>{right}</div>
      </Flex>
      <WhiteSpace/>
    </>
  )
}

function optionSelectionsStringify(selections: catalog.OptionSelection[]): string {
  return _.map(selections, selection => selection.value).join(", ")
}

function addressStringify(address: customer.CustomerAddress) {
  return `${address.location}${address.address}`
}

export default function ProductDetail() {
  const { id } = useParams()
  const history = useHistory()
  const [product, setProduct] = useState(new store.Product())
  const [variant, setVariant] = useState(new store.ProductVariant())
  const [openDrawer, setOpenDrawer] = useState(false)
  const [selections, setSelections] = useState([] as catalog.OptionSelection[])
  const [quantity, setQuantity] = useState(1)
  const [customerAddress, setCustomerAddress] = useState(new customer.CustomerAddress())
  const customerId = security.SecurityUserHolder.getUserId()

  useEffect(() => {
    customer.CustomerAddressServiceV1.getDefaultAddress(customerId).then(setCustomerAddress)
  }, [customerId])

  useEffect(() => {
    store.ProductServiceV1.getProduct(id).then(setProduct)
  }, [id])

  useEffect(() => {
    if (_.size(product.variants) > 0) {
      setVariant(product.variants[0])
    }
  }, [product])

  console.log(customerAddress)

  return (
    <Drawer open={openDrawer}
            sidebar={<OptionSelections product={product}
                                       variant={variant}
                                       quantity={quantity}
                                       onChangeQuantity={setQuantity}
                                       selections={selections}
                                       onChangeSelections={setSelections}/>}
            position="bottom"
            onOpenChange={open => setOpenDrawer(open)}
            sidebarStyle={{ background: "#fff" }}>
      <div className={classes.productDetail}>
        <section className={classes.productContent}>
          <ProductImages imageUrls={product.imageUrls}/>
          <ProductCard>
            <ProductPrice price={product.price} size={32}/>
            <WhiteSpace/>
            <div className={classes.productName}>{product.name}</div>
          </ProductCard>
          <WhiteSpace/>
          <ProductCard>
            <CardItem left="发货" right="">
              <Flex>安徽亳州<WingBlank size="sm"><Divider type="vertical"/></WingBlank>
                快递: 免运费</Flex>
            </CardItem>
          </ProductCard>
          <WhiteSpace/>
          <ProductCard>
            <CardItem left="已选"
                      onClick={() => setOpenDrawer(!openDrawer)}>{optionSelectionsStringify(variant.optionSelections)}</CardItem>
            <WhiteSpace/>
            <Divider variant="middle"/>
            <WhiteSpace/>
            <CardItem left="送至">{addressStringify(customerAddress)}</CardItem>
          </ProductCard>
          <WhiteSpace/>
        </section>
        <footer className={classes.productFooter}>
          <WingBlank style={{ height: "100%" }}>
            <Flex alignItems="center" justifyContent="space-between" style={{ height: "100%" }}>
              <IconButton icon={<Icon type="shop"/>}
                          onClick={() => history.push(`/stores/${product.storeId}`)}>店铺</IconButton>
              <IconButton icon={<Icon type="service"/>}>客服</IconButton>
              <IconButton icon={<Icon type="favor"/>}>收藏</IconButton>
              <Space>
                <Button shape="circle" type="primary">加入购物车</Button>
                <Button shape="circle" type="primary">立即购买</Button>
              </Space>
            </Flex>
          </WingBlank>
        </footer>
      </div>
    </Drawer>
  )
}
